package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;


	//分页查询用户
    @GetMapping("/{currentPage}/{pageSize}")
    public Result selectByPage(@PathVariable  int currentPage,@PathVariable int pageSize) throws IOException {
        Page<User> spage = new Page<>(currentPage, pageSize);
        Page<User> page = userService.page(spage);
        List<User> records = page.getRecords();
        long total = page.getTotal();
//        userService.page(page,null);
        PageBean pageBean = new PageBean(records, total);
        if (records!=null){
            return new Result(Code.GET_OK,pageBean,"查询成功");
        }else {
            return new Result(Code.DELETE_ERR,pageBean,"查询失败");
        }
    }
    /**
     * 保存用户
     * @param user 用户数据
     */
    @PostMapping
    public Result add(@RequestBody  User user) {
        boolean save = userService.save(user);
        if (save)
        return new Result(Code.SAVE_OK,"成功",null);
        return new Result(Code.SAVE_ERR,"失败",null);
    }

    /**
     * 根据用户id查询用户
     * @param id 用户id
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        User user=userService.getById(id);
        if (user!=null){
            return new Result(Code.GET_OK,user,"查询成功" );
        }
        return new Result(Code.GET_ERR,null,"查询失败" );
    }

    /**
     * 更新用户
     * @param user 用户数据
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        boolean b = userService.updateById(user);
        if (b){
            return new Result(Code.GET_ERR,null,"查询成功" );
        }else {
            return new Result(Code.GET_ERR,null,"查询失败" );
        }

    }

}
